import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap } from './router.config.js'
import {getAccessToken} from "@/utils/tokenUtil";

import {needLogin} from "@/utils/tokenUtil";

// import store from "@/store";
// hack router push callback
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

const createRouter = () =>
  new Router({
    // mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
    // base: process.env.BASE_URL,
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRouterMap
  })

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

/*设置全局前置导航守卫:
* 1.若当前已有token且跳转到登录首页是，重新导航到home
* 2.若当前没有token且想跳到首页以外的地址，重新导航到登录首页*/
router.beforeEach((to,from,next) => {
  const name = to.name;
  const token = getAccessToken();
  if(!!token && name == "Login" ){
    //已登录且去往登录页面，重定向到个人中心
    next({name:"PersonalCenter"})
  }else if(!!!token && needLogin(to.name)){
    //未登录且去往需要登录的页面，重定向到登录页面
    next({name:"Login"})
  }else{
    //前往指定的目的地
    next();
  }
})

export default router
